class Folder < ActiveRecord::Base
  depends_on :content, 
             :attrs => [:name, :qualified_name, :url, :position, :folder_id], 
             :as => :presentable, :dependent => :destroy

  class << self
    def folder_tree(prune_folder_id)
      prune_folder_id ||= -1
      cond = <<-SQL
        contents.folder_id is null 
        and folders.id <> #{prune_folder_id}
      SQL

      folders = find_with_content :all, 
        :conditions => cond,
        :order => "contents.position"

      rvalue = []

      folders.each do |fldr|
        rvalue << fldr
        rvalue << fldr.subfolders(prune_folder_id).flatten
      end

      rvalue.flatten.compact
    end

  end # class block

  def parent
    fldrs = Folder.find_by_sql <<-SQL
      select folders.* from folders,contents
      where folders.id = contents.folder_id
        and contents.presentable_id = #{self.id}
        and contents.presentable_type = 'Folder'
    SQL
    fldrs[0]
  end

  def update_user_groups(new_user_group_ids = [])
    return if new_user_group_ids.empty?
    # Need to save this to modify sub_contents
    original_user_groups = content.user_groups.dup

		#
		# Removed previously associated user_groups if not checked this time.
		#
		content.user_groups.dup.each do |ug|
			unless new_user_group_ids.include?(ug.id)
				content.user_groups.delete(ug) 
			end
		end

		# 
		# Add in the new user_groups
		#
		new_user_group_ids.each do |id|
			next if content.user_group_ids.include?(id)
			content.user_groups << UserGroup.find(id)
		end

    content.all_children.each do |sub_content|
      reset_contents_user_groups(sub_content, original_user_groups, new_user_group_ids)
    end
  end # update_user_groups

  def reset_contents_user_groups(sub_content, original_user_groups, new_user_group_ids)
		#
		# Removed user groups inherited from parent
		#
    original_user_groups.each do |oug|
      if sub_content.user_group_ids.include?(oug.id)
        sub_content.user_groups.delete(oug)
      end
    end

		# 
		# Add in the new user_groups from the parent
		#
		new_user_group_ids.each do |id|
			next if sub_content.user_groups.include?(id)
			sub_content.user_groups << UserGroup.find(id)
		end
  end # reset_contents_user_groups

  def update_qualified_names
    content.all_children.each do |child|
      child.set_qualified_name
    end
  end

  def subfolders(prune_folder_id)
    prune_folder_id ||= -1
    rvalue = []
    cond = <<-SQL
      contents.folder_id = #{self.id}
      and folders.id <> #{prune_folder_id}
    SQL

    sub_folders = Folder.find_with_content(:all, 
                    :conditions => cond,
                    :order => "contents.position")

    sub_folders.each do |fldr|
      rvalue << fldr
      rvalue << fldr.subfolders(prune_folder_id).flatten
    end

    rvalue.flatten.compact
  end

end
